const fs = require('fs')
const path = require('path')
const logger = require('../../util/logger')

const {
  root,
  target,
} = require('../config')
const {
  regexAtlas,
  regexSkeleton,
  regexName,
} = require('../config/regConfig')
const readAndMatch = require('../../util/readAndMatch')
const createFoldersAndFiles = require('../script/createFoldersAndFiles')
const getFilesStartingWith = require('../../util/getFilesStartingWith')
const copyAndRenameFiles = require('../script/copyAndRenameFiles')

function getModuleRsV0() {
  const filePath = path.join(root, getFilesStartingWith(root, 'vendors').pop())
  const imagesRoot = path.join(root, 'images')
  const regexPattern = regexAtlas
  const regexPattern2 = regexSkeleton
  const regexPattern3 = regexName
  const atlasDatas = readAndMatch(filePath, regexPattern)
  const skeletonDatas = readAndMatch(filePath, regexPattern2)
  const modules = []
  const errList = []

  if (atlasDatas.length !== skeletonDatas.length) {
    return {
      success: false,
      message: '获取材质和模型不匹配，请手动获取……',
    }
  }

  let n = atlasDatas.length
  const nameReg = new RegExp(regexPattern3)
  if (!fs.existsSync(target) || !fs.lstatSync(target).isDirectory()) {
    fs.mkdirSync(target)
  }
  console.log('开始拆解文件……')
  for (let i = 0; i < n; i++) {
    try {
      const skeletonData = skeletonDatas[i]
      const atlasData = atlasDatas[i]

      const fileNameMatch = atlasData.match(nameReg)
      const fileName = fileNameMatch[0].slice(13, -4)
      const skeletonText = skeletonData.slice(24, -3)
      const atlasText = atlasData.slice(13, -2)

      try {
        createFoldersAndFiles(target, fileName, skeletonText, atlasText)
        modules.push(fileName)
        console.log(`${fileName} 拆解完成`)
      } catch (e) {
        errList.push(fileName)
        console.log(`${fileName} 拆解失败`)
      }
    } catch (e) {

    }
  }

  if (modules.length) {
    logger.info(`模型总数：${modules.length}\n模型列表：\n${modules.join('\n')} \n\n`)
    console.log('拆解模型列表……')
    console.log(modules)

    /* 第四步：复制模型图片 */
    console.log('第四步：复制模型图片……')
    logger.info('第四步：复制模型图片……')
    copyAndRenameFiles(imagesRoot, target, modules)

    if (errList.length) {
      console.log('部分模型拆解失败')
      logger.error('部分模型拆解失败')
      logger.error(`拆解失败模型：\n${errList.join('\n')}\n\n`)
    }

    return true
  } else {
    if (errList && errList.length) {
      console.log('拆解模型列表失败')
      logger.error('拆解模型列表失败')
      return false
    } else {
      console.log('未识别到模型，请手工操作')
      logger.error('未识别到模型，请手工操作')
      return false
    }
  }
}

module.exports = getModuleRsV0
